using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;
using System.Data;

namespace BlueLotus7
{
    public sealed class DatabaseOperator : IDisposable
    {
        const int timeoutMillSeconds = 30000;

        SqlConnection sqlConnection;
        SqlCommand sqlCommand;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="databaseConnectionString">The database connection string.</param>
        public DatabaseOperator(string databaseConnectionString)
            : this(new SqlConnection(databaseConnectionString))
        {

        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="databaseConnectionString">The database connection string.</param>
        public DatabaseOperator(SqlConnection sqlConnection)
        {
            try
            {
                this.sqlConnection = sqlConnection;
                this.sqlCommand = sqlConnection.CreateCommand();
                sqlCommand.Connection = sqlConnection;
                sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
            }
            catch (Exception ex)
            {
                throw new Exception("Fail to initialize DatabaseOperator.", ex);
            }
        }



        #region Execute procedures

        /// <summary>
        /// Execute reader.
        /// </summary>
        /// <param name="ProcedureName">The procedure name.</param>
        /// <param name="sqlParameters">The sql parameters.</param>
        /// <returns>The SqlDataReader contains datas.</returns>
        public SqlDataReader ExecuteReader(string procedureName, List<SqlParameter> sqlParameters)
        {
            CheckPrecedureName(procedureName);
            try
            {
                sqlCommand.CommandText = procedureName;
                sqlCommand.Parameters.Clear();
                sqlCommand.CommandTimeout = timeoutMillSeconds;
                if (sqlParameters != null)
                    sqlCommand.Parameters.AddRange(sqlParameters.ToArray());
                if (sqlConnection.State != ConnectionState.Open)
                {
                    sqlConnection.Open();
                }
                return sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Fail to execute procedure [{0}]", procedureName), ex);
            }
        }

        /// <summary>
        /// Execute reader.
        /// </summary>
        /// <param name="ProcedureName">The procedure name.</param>
        /// <returns>The SqlDataReader contains datas.</returns>
        public SqlDataReader ExecuteReader(string procedureName)
        {
            return ExecuteReader(procedureName, null);
        }

        /// <summary>
        /// Execute scalar
        /// </summary>
        /// <param name="procedureName">The procedure name.</param>
        /// <param name="sqlParameters">The sql parameters.</param>
        /// <returns>The first column in first row of result data.</returns>
        public object ExecuteScalar(string procedureName, List<SqlParameter> sqlParameters)
        {
            CheckPrecedureName(procedureName);

            object result = null;
            try
            {
                sqlCommand.CommandText = procedureName;
                sqlCommand.Parameters.Clear();
                sqlCommand.CommandTimeout = timeoutMillSeconds;
                if (sqlParameters != null)
                    sqlCommand.Parameters.AddRange(sqlParameters.ToArray());
                if (sqlConnection.State != ConnectionState.Open)
                {
                    sqlConnection.Open();
                }
                result = sqlCommand.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Fail to execute procedure [{0}]", procedureName), ex);
            }

            return result;
        }

        /// <summary>
        /// Execute scalar
        /// </summary>
        /// <returns>The first column in first row of result data.</returns>
        public object ExecuteScalar(string procedureName)
        {
            return ExecuteScalar(procedureName, null);
        }

        /// <summary>
        /// Execute none query.
        /// </summary>
        /// <param name="procedureName">The procedure name.</param>
        /// <param name="sqlParameters">The sql parameters.</param>
        /// <returns>The count of row influenced.</returns>
        public int ExecuteNonQuery(string procedureName, List<SqlParameter> sqlParameters)
        {
            CheckPrecedureName(procedureName);

            int count = 0;
            try
            {
                sqlCommand.CommandText = procedureName;
                sqlCommand.Parameters.Clear();
                sqlCommand.CommandTimeout = timeoutMillSeconds;
                if (sqlParameters != null)
                    sqlCommand.Parameters.AddRange(sqlParameters.ToArray());
                if (sqlConnection.State != ConnectionState.Open)
                {
                    sqlConnection.Open();
                }
                count = sqlCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Fail to execute procedure [{0}]", procedureName), ex);
            }

            return count;
        }

        /// <summary>
        /// Execute none query.
        /// </summary>
        /// <param name="procedureName">The procedure name.</param>
        /// <returns>The count of row influenced.</returns>
        public int ExecuteNonQuery(string procedureName)
        {
            return ExecuteNonQuery(procedureName, null);
        }

        #endregion

        private void CheckPrecedureName(string procedureName)
        {
            if (string.IsNullOrWhiteSpace(procedureName))
            {
                throw new NullReferenceException("procedureName");
            }
        }

        public void Dispose()
        {
            if (sqlConnection != null)
            {
                try
                {
                    sqlConnection.Close();
                }
                catch { }
                sqlConnection.Dispose();
            }
        }
    }
}
